package com.yupi.springbootinit.ws;

import com.alibaba.fastjson.JSON;
import com.yupi.springbootinit.config.GetHttpSessionConfigurator;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.utils.MessageUtils;
import com.yupi.springbootinit.utils.ResultMessage;
import com.yupi.springbootinit.ws.pojo.Message;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.bridge.MessageUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
@Component
@Slf4j
public class ChatEndpoint {

    private static final Map<String,Session> onlineUsers=new ConcurrentHashMap<>();

    private HttpSession httpSession;

    private String currentUsername;



    /**
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        //1.将session进行保存

        this.httpSession=(HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        User user =(User) this.httpSession.getAttribute(USER_LOGIN_STATE);
        String username= user.getUserName();
        this.currentUsername=username;
        onlineUsers.put(username,session);
        ResultMessage result=new ResultMessage();
        result.setSender("0");
        result.setContent("系统消息,用户"+username+"上线了");
        broadcastAllUsers(JSON.toJSONString(result));
        log.info("用户"+username+"上线了");
        //2.广播消息，将登录的所用用户推给所有用户
//        String message=MessageUtils.getMessage(true,username,getFriends());
//        broadcastAllUsers(message);
    }

    public Set getFriends(){
        Set<String> set=onlineUsers.keySet();
        return set;
    }

    private void broadcastAllUsers(String message){
        try{
            Set<Map.Entry<String,Session>> entries=onlineUsers.entrySet();
            for (Map.Entry<String, Session> entry : entries) {
                //获取所有用户对应的session对象

                Session session= entry.getValue();
                log.info("目前是谁"+session);
                if(currentUsername.equals(entry.getKey())){
                    continue;
                }
                //发送消息
                session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){

        }
    }


    /**
     * 浏览器发送消息到服务器，该方法会被调用
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        try{
            //将消息推送给指定的用户
            Message msg=JSON.parseObject(message,Message.class);
            //获取消息接受发用户名
//            String toName=msg.getSender();
//            String mess=msg.getContent();
//            //获取消息接收方的对象的session对象
//            Session session=onlineUsers.get(toName);
//            User user =(User) this.httpSession.getAttribute(USER_LOGIN_STATE);
//            log.info("服务器向浏览器发生"+msg);
//            //session.getBasicRemote().sendText(JSON.toJSONString(msg));
            broadcastAllUsers(JSON.toJSONString(msg));
        } catch (Exception e){
            //
        } finally {
            log.info("浏览器向服务器发送了一条消息"+message);
        }
    }

    @OnClose
    public void onClose(Session session){
        //1.从onlineUsers中删除所有登录用户
        User user =(User) this.httpSession.getAttribute(USER_LOGIN_STATE);
        String username= user.getUserName();
        onlineUsers.remove(username);
        //2.通知所有用户，当前用户下线了
        String message=MessageUtils.getMessage(true,username,getFriends());
        broadcastAllUsers(message);
    }
}
